package com.yuexunit.finance.thread;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TimerTask;

import javax.persistence.Column;

import org.hibernate.Session;

import com.yuexunit.core.BusinessException;
import com.yuexunit.finance.bulkstock.service.TemporaryCreditLineService;
import com.yuexunit.finance.bulkstock.service.TemporaryCreditlineEvaluationService;
import com.yuexunit.finance.common.util.CollectionUtils;
import com.yuexunit.finance.common.util.DateUtils;
import com.yuexunit.finance.member.entity.EnterpriseEntity;
import com.yuexunit.finance.member.entity.EnterpriseGradeEntity;
import com.yuexunit.finance.member.entity.EnterpriseGradeEvaluationEntity;
import com.yuexunit.finance.member.entity.MonthBillEntity;
import com.yuexunit.finance.member.entity.MonthEarningDetailEntity;
import com.yuexunit.finance.member.entity.MonthEarningEntity;
import com.yuexunit.finance.member.entity.TemporaryCreditLineEntity;
import com.yuexunit.finance.member.entity.TemporaryCreditlineEvaluationEntity;
import com.yuexunit.finance.member.entity.lexicon.AuditStateEnum;
import com.yuexunit.finance.member.service.EnterpriseGradeEvaluationService;
import com.yuexunit.finance.member.service.EnterpriseGradeService;
import com.yuexunit.finance.member.service.EnterpriseService;
import com.yuexunit.finance.member.service.MonthBillService;
import com.yuexunit.finance.member.service.MonthEarningDetailService;
import com.yuexunit.finance.member.service.MonthEarningService;
import com.yuexunit.finance.project.entity.ContainerBulkstockEntity;
import com.yuexunit.finance.project.entity.ContainerInventoryEntity;
import com.yuexunit.finance.project.entity.FinanceApplicationEntity;
import com.yuexunit.finance.project.entity.FinanceAuditEntity;
import com.yuexunit.finance.project.entity.FinanceBulkstockEntity;
import com.yuexunit.finance.project.entity.FinanceMoneyStatementEntity;
import com.yuexunit.finance.project.entity.PickupApplicationEntity;
import com.yuexunit.finance.project.entity.WarningSchemeEntity;
import com.yuexunit.finance.project.entity.WarningSchemeResultEntity;
import com.yuexunit.finance.project.entity.lexicon.ApplicationStateEnum;
import com.yuexunit.finance.project.entity.lexicon.FinanceStateEnum;
import com.yuexunit.finance.project.entity.lexicon.PickupMethodEnum;
import com.yuexunit.finance.project.entity.lexicon.ProductTypeEnum;
import com.yuexunit.finance.project.entity.lexicon.RelationTypeEnum;
import com.yuexunit.finance.project.entity.lexicon.SettlementStateEnum;
import com.yuexunit.finance.project.entity.lexicon.WarningFactorEnum;
import com.yuexunit.finance.project.entity.lexicon.WarningLevelEnum;
import com.yuexunit.finance.project.service.ContainerBulkstockService;
import com.yuexunit.finance.project.service.ContainerInventoryService;
import com.yuexunit.finance.project.service.FinanceApplicationService;
import com.yuexunit.finance.project.service.FinanceAuditService;
import com.yuexunit.finance.project.service.FinanceBulkstockService;
import com.yuexunit.finance.project.service.FinanceMoneyStatementService;
import com.yuexunit.finance.project.service.PickupApplicationService;
import com.yuexunit.finance.project.service.WarningSchemeResultService;
import com.yuexunit.finance.project.service.WarningSchemeService;
import com.yuexunit.finance.statement.entity.DaysEarningEntity;
import com.yuexunit.finance.statement.entity.EarningSummaryEntity;
import com.yuexunit.finance.statement.service.DaysEarningService;
import com.yuexunit.finance.statement.service.EarningSummaryService;
import com.yuexunit.finance.system.action.v1.SystemParamActionApi;
import com.yuexunit.finance.tatistics.entity.EnterpriseFinanceSummaryEntity;
import com.yuexunit.finance.tatistics.service.EnterpriseFinanceSummaryService;
import com.yuexunit.inject.ComponentFactory;
import com.yuexunit.page.PageCriteria;
import com.yuexunit.persist.annotation.Transactional;
import com.yuexunit.persist.hibernate.SessionRepository;
import com.yuexunit.util.DateUtil;
import com.yuexunit.util.StringUtil;

/**
 *@version 创建时间：2016年8月31日 上午10:29:28
 *@author wenwenlong
 *类说明
 */

public class EnterpriseSummaryTimeTask extends TimerTask {
	@Override
	@Transactional
	public void run() {
		//		countEnterpriseSummary();
		//		countEnterpriseGradeEvaluation();
		//		countEnterpriseTemporaryEvaluation();
		//		initEnterpriseEnterprise();
		//		autoCountInterest();
		autoCountDaysInterest(null, null, null);
		autoCountMonthInterest(null, null, null, null);
		financeDelayWarning();
	}

	@Transactional
	public void run1(){
		countEnterpriseSummary();
		countEnterpriseGradeEvaluation();
		countEnterpriseTemporaryEvaluation();
		//		initEnterpriseEnterprise();
		//		amendFinanceValuation();
	}

	//统计企业信息
	private void countEnterpriseSummary(){
		EnterpriseFinanceSummaryService enterpriseFinanceSummaryService = ComponentFactory.loadClass(EnterpriseFinanceSummaryService.class);
		//		enterpriseFinanceSummaryService.callProcedure();

		EnterpriseService enterpriseService = ComponentFactory.loadClass(EnterpriseService.class);
		EnterpriseGradeService enterpriseGradeService = ComponentFactory.loadClass(EnterpriseGradeService.class);
		FinanceApplicationService financeApplicationService = ComponentFactory.loadClass(FinanceApplicationService.class);
		PickupApplicationService pickupApplicationService = ComponentFactory.loadClass(PickupApplicationService.class);
		FinanceBulkstockService financeBulkstockService = ComponentFactory.loadClass(FinanceBulkstockService.class);
		FinanceMoneyStatementService financeMoneyStatementService = ComponentFactory.loadClass(FinanceMoneyStatementService.class);

		List<Long> enterpriseIds = enterpriseService.countAuditedClients();
		for (Long enterpriseId : enterpriseIds) {
			EnterpriseFinanceSummaryEntity summary = enterpriseFinanceSummaryService.inquireEnterpriseFinanceSummaryDetail(enterpriseId);
			EnterpriseEntity enterprise = enterpriseService.inquireEnterprise(enterpriseId);
			if (summary == null) {
				summary = new EnterpriseFinanceSummaryEntity();
				summary.setEnterpriseId(enterpriseId);
				summary.setEnterpriseName(enterprise.getEnterpriseName());
			}

			EnterpriseGradeEntity grade = enterpriseGradeService.inquireEnterpriseGrade(enterpriseId);

			Set<ApplicationStateEnum> applicationState = CollectionUtils.convertSet(ApplicationStateEnum.values());
			applicationState.remove(ApplicationStateEnum.UNKNOWN);
			applicationState.remove(ApplicationStateEnum.NOT_APPROVE);
			applicationState.remove(ApplicationStateEnum.AGREE);
			applicationState.remove(ApplicationStateEnum.DISAGREE);
			applicationState.remove(ApplicationStateEnum.VIOLATE);
			applicationState.remove(ApplicationStateEnum.CANCEL);
			List<PickupApplicationEntity> pickupList = pickupApplicationService.inquirePickupApplicationList(enterpriseId, applicationState, PickupMethodEnum.CASH_DELIVERY, null, null, null, null);

			// 扣除 状态为 取消/审批不通过/待确认/已完成/已评价
			Set<FinanceStateEnum> financeStates = CollectionUtils.convertSet(FinanceStateEnum.values());
			financeStates.remove(FinanceStateEnum.WAIT_CONFIRM);
			financeStates.remove(FinanceStateEnum.CANCEL);
			financeStates.remove(FinanceStateEnum.APPROVE_NOPASS);
			financeStates.remove(FinanceStateEnum.FINISH);
			financeStates.remove(FinanceStateEnum.EVALUATE);
			//进行中的融资申请
			List<FinanceApplicationEntity> applicationList = financeApplicationService.inquireInProcessFinanceApplicationList(enterpriseId, financeStates);

			//进行中的融资总额
			BigDecimal inFinanceAmount = BigDecimal.ZERO;
			//进行中货物总值
			BigDecimal inBulkstockValuation = BigDecimal.ZERO;
			//进行中的已放款总额
			BigDecimal inLoanAmount = BigDecimal.ZERO;
			//进行中的已收款总额
			BigDecimal inReceivables = BigDecimal.ZERO;
			//进行中的未收总额
			BigDecimal inRemindAmount = BigDecimal.ZERO;
			//进行中在押货物总额
			BigDecimal inIncustodyAmount = BigDecimal.ZERO;

			BigDecimal pickupAmount = BigDecimal.ZERO;
			for (PickupApplicationEntity pae : pickupList) {
				pickupAmount = pickupAmount.add(pae.getFinanceValuation());
			}

			for (FinanceApplicationEntity fae : applicationList) {
				inFinanceAmount = inFinanceAmount.add(fae.getFinanceAmount());
				List<FinanceBulkstockEntity> fbes = financeBulkstockService.inquireFinanceBulkstockList(fae.getFinanceId());
				for (FinanceBulkstockEntity fbe : fbes) {
					inBulkstockValuation = inBulkstockValuation.add(fbe.getEvaluatePrice().multiply(fbe.getValuationQuantity()).setScale(2, BigDecimal.ROUND_HALF_UP));
					inIncustodyAmount = inIncustodyAmount.add(fbe.getFinancePrice().multiply(fbe.getValuationQuantity()));
				}
				List<FinanceMoneyStatementEntity> dfmses = financeMoneyStatementService.inquireFinanceMoneyDisbursementStatementList(null, fae.getFinanceId(), new String[]{"LOAN_NOTICE"});
				for (FinanceMoneyStatementEntity dfmse : dfmses) {
					inLoanAmount = inLoanAmount.add(dfmse.getAmount().subtract(dfmse.getReceiptBalance()));
				}

				List<FinanceMoneyStatementEntity> rfmses = financeMoneyStatementService.inquireFinanceMoneyReceiptStatementList(null, fae.getFinanceId(), new String[]{"RECEIVABLES"});
				for (FinanceMoneyStatementEntity rfmse : rfmses) {
					inReceivables = inReceivables.add(rfmse.getAmount().subtract(rfmse.getDisbursementBalance()));
					inRemindAmount = inRemindAmount.add(rfmse.getDisbursementBalance());
				}
			}

			summary.setInFinanceAmount(inFinanceAmount);
			summary.setInBulkstockValuation(inBulkstockValuation);
			summary.setInLoanAmount(inLoanAmount);
			summary.setInReceivables(inReceivables);
			summary.setInRemindAmount(inRemindAmount);
			summary.setInIncustodyAmount(inIncustodyAmount);
			//进行中的融资数
			if (applicationList != null) {
				summary.setProgressing(applicationList.size());
			}

			if (grade == null) {
				summary.setCreditLine(BigDecimal.ZERO);
				summary.setCreditLineAlready(BigDecimal.ZERO);
			} else {
				summary.setCreditLine(grade.getCreditLine());
				summary.setCreditLineAlready(grade.getCreditAlready());
			}
			summary.setEnterpriseType(enterprise.getEnterpriseType());
			summary.setUpdateDateTime(DateUtil.now());
			enterpriseFinanceSummaryService.updateEnterpriseFinanceSummary(summary);
		}
	}

	//企业等级调整
	public void countEnterpriseGradeEvaluation() {
		EnterpriseGradeService enterpriseGradeService = ComponentFactory.loadClass(EnterpriseGradeService.class);
		EnterpriseGradeEvaluationService enterpriseGradeEvaluationService = ComponentFactory.loadClass(EnterpriseGradeEvaluationService.class);
		EnterpriseService enterpriseService = ComponentFactory.loadClass(EnterpriseService.class);
		List<EnterpriseEntity> entities = enterpriseService.inquireEnterpriseList(null);
		for (EnterpriseEntity ee : entities) {
			EnterpriseGradeEvaluationEntity egee = enterpriseGradeEvaluationService.inquireEnterpriseGradeEvaluation(ee.getEnterpriseId());
			EnterpriseGradeEntity grade = enterpriseGradeService.inquireEnterpriseGrade(ee.getEnterpriseId());
			if (grade != null && grade.getEffectiveEndDate() < DateUtil.todayInt()) {
				grade.setEffective(Boolean.FALSE);
				enterpriseGradeService.persistEnterpriseGrade(grade);
			}
			if (egee == null) {
				continue;
			}
			if (egee.getEffectiveStartDate() != null && egee.getEffectiveEndDate() != null && egee.getEffectiveStartDate() <= DateUtil.todayInt() && egee.getEffectiveEndDate() >= DateUtil.todayInt()) {
				if (grade != null) {
					grade.setGradeEvaluationId(egee.getGradeEvaluationId());
					grade.setMemberGradeId(egee.getMemberGradeId());
					grade.setGradeName(egee.getGradeName());
					grade.setInterestRate(egee.getInterestRate());
					grade.setPenalInterest(egee.getPenalInterest());
					grade.setCreditLine(egee.getCreditLine());
					grade.setEffective(Boolean.TRUE);
					grade.setEffectiveEndDate(egee.getEffectiveEndDate());
					grade.setEffectiveStartDate(egee.getEffectiveStartDate());
					enterpriseGradeService.persistEnterpriseGrade(grade);
				} else {
					grade = new EnterpriseGradeEntity();
					grade.setEnterpriseId(egee.getEnterpriseId());
					grade.setGradeEvaluationId(egee.getGradeEvaluationId());
					grade.setMemberGradeId(egee.getMemberGradeId());
					grade.setGradeName(egee.getGradeName());
					grade.setInterestRate(egee.getInterestRate());
					grade.setPenalInterest(egee.getPenalInterest());
					grade.setCreditLine(egee.getCreditLine());
					grade.setEffective(Boolean.TRUE);
					grade.setEffectiveEndDate(egee.getEffectiveEndDate());
					grade.setEffectiveStartDate(egee.getEffectiveStartDate());
					enterpriseGradeService.createEnterpriseGrade(grade);
				}
			}
		}
	}

	//企业临时额度
	private void countEnterpriseTemporaryEvaluation() {
		TemporaryCreditlineEvaluationService temporaryCreditlineEvaluationService = ComponentFactory.loadClass(TemporaryCreditlineEvaluationService.class);
		TemporaryCreditLineService temporaryCreditLineService = ComponentFactory.loadClass(TemporaryCreditLineService.class);
		EnterpriseService enterpriseService = ComponentFactory.loadClass(EnterpriseService.class);
		List<EnterpriseEntity> entities = enterpriseService.inquireEnterpriseList(null);
		for (EnterpriseEntity ee : entities) {
			TemporaryCreditlineEvaluationEntity tcee = temporaryCreditlineEvaluationService.inquireTemporaryCreDitlineEvaluationFromEnterpriseId(ee.getEnterpriseId());
			TemporaryCreditLineEntity tcle = temporaryCreditLineService.inquireTemporaryCreditLine1(ee.getEnterpriseId());
			if (tcle != null && tcle.getEffectiveEndDate() < DateUtil.todayInt()) {
				tcle.setEffective(Boolean.FALSE);
				temporaryCreditLineService.updateTemporaryCreditLine(tcle);
			}
			if (tcee == null) {
				continue;
			}
			if (tcee.getEffectiveStartDate() !=null && (tcee.getAuditState() == AuditStateEnum.PASS || tcee.getAuditState() == AuditStateEnum.FINISH) && tcee.getEffectiveEndDate() != null && tcee.getEffectiveStartDate() <= DateUtil.todayInt() && tcee.getEffectiveEndDate() >= DateUtil.todayInt()) {
				if (tcle != null) {
					tcle.setTemporaryCreditlineEvaluationId(tcee.getTemporaryCreditlineEvaluationId());
					tcle.setTemporaryCreditline(tcee.getTemporaryCreditline());
					tcle.setTemporaryCreditlineAlready(BigDecimal.ZERO);
					tcle.setEffective(Boolean.TRUE);
					tcle.setEffectiveEndDate(tcee.getEffectiveEndDate());
					tcle.setEffectiveStartDate(tcee.getEffectiveStartDate());
					temporaryCreditLineService.updateTemporaryCreditLine(tcle);
				} else {
					tcle = new TemporaryCreditLineEntity();
					tcle.setEnterpriseId(ee.getEnterpriseId());
					tcle.setTemporaryCreditlineEvaluationId(tcee.getTemporaryCreditlineEvaluationId());
					tcle.setTemporaryCreditline(tcee.getTemporaryCreditline());
					tcle.setTemporaryCreditlineAlready(BigDecimal.ZERO);
					tcle.setEffective(Boolean.TRUE);
					tcle.setEffectiveEndDate(tcee.getEffectiveEndDate());
					tcle.setEffectiveStartDate(tcee.getEffectiveStartDate());
					temporaryCreditLineService.createTemporaryCreditLine(tcle);
				}
			}
		}
	}

	@Transactional
	public void amendFinanceValuation() {
		String str = "";
		PageCriteria page = PageCriteria.defaultInstance();
		page.setPageSize(10000);
		ContainerInventoryService containerInventoryService = ComponentFactory.loadClass(ContainerInventoryService.class);
		ContainerBulkstockService containerBulkstockService = ComponentFactory.loadClass(ContainerBulkstockService.class);
		FinanceApplicationService financeApplicationService = ComponentFactory.loadClass(FinanceApplicationService.class);
		FinanceAuditService financeAuditService = ComponentFactory.loadClass(FinanceAuditService.class);
		FinanceMoneyStatementService financeMoneyStatementService = ComponentFactory.loadClass(FinanceMoneyStatementService.class);

		// 扣除 状态为 取消/审批不通过/待确认/已完成/已评价
		Set<FinanceStateEnum> financeStates = CollectionUtils.convertSet(FinanceStateEnum.values());
		financeStates.remove(FinanceStateEnum.WAIT_CONFIRM);
		financeStates.remove(FinanceStateEnum.CANCEL);
		financeStates.remove(FinanceStateEnum.APPROVE_NOPASS);
		financeStates.remove(FinanceStateEnum.FINISH);
		financeStates.remove(FinanceStateEnum.EVALUATE);
		//进行中的融资申请
		List<FinanceApplicationEntity> applicationList = financeApplicationService.inquireInProcessFinanceApplicationList(null, financeStates);
		for (FinanceApplicationEntity fae : applicationList) {
			FinanceAuditEntity faue = financeAuditService.inquireLatestFinanceAudit(fae.getFinanceId());
			if (faue == null || faue.getRiskSubmitState() != Boolean.TRUE || faue.getRiskAuditState() != Boolean.TRUE) {
				continue;
			}

			BigDecimal receiptAmount = BigDecimal.ZERO;
			BigDecimal loanAmount = BigDecimal.ZERO;

			List<FinanceMoneyStatementEntity> fmses = financeMoneyStatementService.inquireFinanceMoneyReceiptStatementList(null, fae.getFinanceId(), new String[]{"RECEIVABLES"});
			for (FinanceMoneyStatementEntity fmse : fmses) {
				receiptAmount = receiptAmount.add(fmse.getReceiptAmount());
			}
			List<FinanceMoneyStatementEntity> fmses1 = financeMoneyStatementService.inquireFinanceMoneyReceiptStatementList(null, fae.getFinanceId(), new String[]{"LOAN_NOTICE"});
			for (FinanceMoneyStatementEntity fmse : fmses1) {
				loanAmount = loanAmount.add(fmse.getDisbursementAmount());
			}

			BigDecimal amount = BigDecimal.ZERO;
			BigDecimal valuationQuantity = BigDecimal.ZERO;
			List<ContainerInventoryEntity> cies = containerInventoryService.inquireContainerInventoryList(fae.getFinanceId(), null);
			for (ContainerInventoryEntity cie : cies) {
				if (cie.getPickupId() != null) {
					continue;
				}
				List<ContainerBulkstockEntity> cbes = containerBulkstockService.inquireContainerBulkstockList(cie.getInventoryId());
				for (ContainerBulkstockEntity cbe : cbes) {
					valuationQuantity = valuationQuantity.add(cbe.getValuationQuantity());
					amount = amount.add(cbe.getValuationFinanceAmount());
				}
				if (cie.getAdjustment() != null) {
					amount = amount.add(cie.getAdjustment());
				}
				cie.setAdjustment(BigDecimal.ZERO);
				containerInventoryService.updateContainerInventory(cie);
			}
			if (valuationQuantity == null || valuationQuantity == BigDecimal.ZERO) {
				continue;
			}
			BigDecimal financePrice = (fae.getFinanceAmount().subtract(receiptAmount)).divide(valuationQuantity, 2, BigDecimal.ROUND_HALF_UP);
			BigDecimal adjustment = (fae.getFinanceAmount().subtract(receiptAmount)).subtract(financePrice.multiply(valuationQuantity));

			Integer j = null;
			for (int i = 0; i < cies.size(); i++) {
				ContainerInventoryEntity cie = cies.get(i);
				if (cie.getPickupId() != null) {
					continue;
				} else {
					j = i;
				}
				List<ContainerBulkstockEntity> cbes = containerBulkstockService.inquireContainerBulkstockList(cie.getInventoryId());
				for (ContainerBulkstockEntity cbe : cbes) {
					cbe.setFinancePrice(financePrice);
					containerBulkstockService.updateContainerBulkstock(cbe);
				}
			}

			ContainerInventoryEntity last = cies.get(j);
			last.setAdjustment(adjustment);
			containerInventoryService.updateContainerInventory(last);
			str+="financeId=" + fae.getFinanceId() + ",financeNumber= " + fae.getFinanceNumber() + ", financeAmount =" + fae.getFinanceAmount() + ", receiptAmount =" + receiptAmount + " loanAmount =" + loanAmount + ", amount =" + amount + ", financePrice = " + financePrice + " adjustment =" + adjustment + "/n";
		}

		System.out.println(str);
	}

	//自动计息
	private void autoCountInterest() {
		Calendar c = Calendar.getInstance();
		if (c.get(Calendar.DATE) != 20) {
			return;
		}
	}

	//自动计息
	@Transactional
	public void autoCountDaysInterest(String enterpriseName, String financeNumber, Integer date) {
		if (date == null) {
			date = DateUtils.parseDateInt(DateUtils.addDateField(DateUtil.now(), Calendar.DATE, -1));
		}

		if(date >= DateUtil.todayInt()) {
			throw new BusinessException("该日期暂不能生成！");
		}
		EarningSummaryService earningSummaryService = ComponentFactory.loadClass(EarningSummaryService.class);
		EarningSummaryEntity ese = null;
		List<EarningSummaryEntity> eses = earningSummaryService.inquireEarningSummaryList(date);
		if (eses != null && eses.size() > 0) {
			ese = eses.get(0);
		} else {
			ese = new EarningSummaryEntity();
		}

		//今日收益
		DaysEarningService daysEarningService = ComponentFactory.loadClass(DaysEarningService.class);
		StringBuffer sql = new StringBuffer("SELECT FINANCE_ID, FINANCE_NUMBER, ENTERPRISE_NAME, ENTERPRISE_ID, STATEMENT_D8, PRODUCT_TYPE, SUM(DISBURSEMENT_AMOUNT) AS DISBURSEMENT_AMOUNT, SUM(RECEIPT_AMOUNT) AS RECEIPT_AMOUNT , SUM(DISBURSEMENT_AMOUNT) - SUM(RECEIPT_AMOUNT) AS AMOUNT , INTEREST / (100 * 360) * (SUM(DISBURSEMENT_AMOUNT) - SUM(RECEIPT_AMOUNT)) AS FEE , INTEREST, FINANCE_STATE FROM view_fin_days_earning v WHERE 1 = 1");
		if (StringUtil.isNotBlank(enterpriseName)) {
			sql.append(" AND v.ENTERPRISE_NAME = '" + enterpriseName + "'");
		}

		if (StringUtil.isNotBlank(financeNumber)) {
			sql.append(" AND v.FINANCE_NUMBER = '" + financeNumber + "'");
		}

		if (date != null) {
			sql.append(" AND v.STATEMENT_D8 <= " + date);
		}

		sql.append(" GROUP BY FINANCE_ID");
		Session session = SessionRepository.getCurrentSession();
		List<Object> datas = session.createSQLQuery(sql.toString()).addScalar("FINANCE_ID").addScalar("FINANCE_NUMBER").addScalar("ENTERPRISE_NAME").addScalar("PRODUCT_TYPE").addScalar("DISBURSEMENT_AMOUNT").addScalar("RECEIPT_AMOUNT").addScalar("AMOUNT").addScalar("FEE").addScalar("INTEREST").addScalar("FINANCE_STATE").addScalar("STATEMENT_D8").addScalar("ENTERPRISE_ID").list();
		for (Object l : datas) {
			Object[] os = (Object[])l;
			if (BigDecimal.ZERO.compareTo((BigDecimal) os[7]) >= 0) {
				continue;
			}

			List<DaysEarningEntity> dees = daysEarningService.inquireDaysEarningList(((BigInteger) os[0]).longValue(), date, null, null);
			DaysEarningEntity entity = null;
			if (dees != null && dees.size() > 0) {
				entity = dees.get(0);
			} else {
				entity = new DaysEarningEntity();
			}
			entity.setFinanceId(((BigInteger) os[0]).longValue());
			entity.setFinanceNumber((String) os[1]);
			entity.setEnterpriseName((String) os[2]);
			entity.setProductType(ProductTypeEnum.valueOf(((Byte) os[3]).intValue()));
			entity.setCreator("系统自动生成");
			entity.setFinanceAmount((BigDecimal) os[4]);
			entity.setBulkstockValuation((BigDecimal) os[6]);
			entity.setInterest((BigDecimal) os[7]);
			entity.setInterestRate((BigDecimal) os[8]);
			entity.setFinanceState(FinanceStateEnum.valueOf(((Byte) os[9]).intValue()));
			if (date != null) {
				entity.setInterestDate(date);
			} else {
				entity.setInterestDate(DateUtils.parseDateInt(DateUtils.addDateField(DateUtil.now(), Calendar.DATE, -1)));
			}
			entity.setEarningDate(DateUtils.addDateField(DateUtil.now(), Calendar.DATE, -1));
			entity.setLoanDate(((Integer) os[10]).intValue());
			entity.setEnterpriseId(((BigInteger) os[11]).longValue());
			daysEarningService.createDaysEarning(entity);
		}

		sql = new StringBuffer("SELECT SUM(a.DISBURSEMENT_AMOUNT) DISBURSEMENT_AMOUNT FROM fin_finance_money_statement a WHERE a.STATEMENT_SOURCE = 'LOAN_NOTICE'");
		sql.append(" AND a.STATEMENT_D8 <= " + date);
		session = SessionRepository.getCurrentSession();
		datas = session.createSQLQuery(sql.toString()).addScalar("DISBURSEMENT_AMOUNT").list();
		for (Object l : datas) {
			Object os = (Object)l;
			ese.setLoanAmount((BigDecimal) os);
		}

		//总收益
		sql = new StringBuffer("SELECT SUM(b.INTEREST) INTEREST FROM fin_days_earning b WHERE 1 = 1");
		//		sql.append(" AND b.INTEREST_DT <= " + date);
		session = SessionRepository.getCurrentSession();
		datas = session.createSQLQuery(sql.toString()).addScalar("INTEREST").list();
		for (Object l : datas) {
			Object os = (Object)l;
			ese.setTotalEarning((BigDecimal) os);
		}

		//昨日收益
		sql = new StringBuffer("SELECT SUM(b.INTEREST) INTEREST FROM fin_days_earning b WHERE 1 = 1");
		sql.append(" AND b.INTEREST_DT <= " + DateUtils.parseDateInt(DateUtils.addDateField(DateUtils.fromDateInt(date), Calendar.DATE, -1)));
		session = SessionRepository.getCurrentSession();
		datas = session.createSQLQuery(sql.toString()).addScalar("INTEREST").list();
		for (Object l : datas) {
			Object os = (Object)l;
			ese.setYestodayEarning((BigDecimal) os);
		}

		//前一日数据
		List<EarningSummaryEntity> eses1 = earningSummaryService.inquireEarningSummaryList(DateUtils.parseDateInt(DateUtils.addDateField(DateUtils.fromDateInt(date), Calendar.DATE, -1)));
		if (eses1 != null && eses1.size() > 0) {
			EarningSummaryEntity ese1 = eses1.get(0);

			if (BigDecimal.ZERO.compareTo(ese1.getLoanAmount()) == 0) {
				ese.setLoanAmountIncrease(BigDecimal.ZERO);
			} else {
				ese.setLoanAmountIncrease((ese.getLoanAmount().subtract(ese1.getLoanAmount())).divide(ese1.getLoanAmount(), 2, BigDecimal.ROUND_HALF_UP));
			}
			ese.setLoanAmountRiseFall(ese.getLoanAmount().subtract(ese1.getLoanAmount()));

			if (BigDecimal.ZERO.compareTo(ese1.getYestodayEarning()) == 0) {
				ese.setYestodayEarningIncrease(BigDecimal.ZERO);
			} else {
				ese.setYestodayEarningIncrease((ese.getYestodayEarning().subtract(ese1.getYestodayEarning())).divide(ese1.getYestodayEarning(), 2, BigDecimal.ROUND_HALF_UP));
			}
			ese.setYestodayEarningRiseFall(ese.getYestodayEarning().subtract(ese1.getYestodayEarning()));

			if (BigDecimal.ZERO.compareTo(ese1.getTotalEarning()) == 0) {
				ese.setTotalEarningIncrease(BigDecimal.ZERO);
			} else {
				ese.setTotalEarningIncrease((ese.getTotalEarning().subtract(ese1.getTotalEarning())).divide(ese1.getTotalEarning(), 2, BigDecimal.ROUND_HALF_UP));
			}
			ese.setTotalEarningRiseFall(ese.getTotalEarning().subtract(ese1.getTotalEarning()));
		} else {
			ese.setLoanAmountIncrease(BigDecimal.ZERO);
			ese.setLoanAmountRiseFall(BigDecimal.ZERO);
			ese.setYestodayEarningIncrease(BigDecimal.ZERO);
			ese.setYestodayEarningRiseFall(BigDecimal.ZERO);
			ese.setTotalEarningIncrease(BigDecimal.ZERO);
			ese.setTotalEarningRiseFall(BigDecimal.ZERO);
		}
		ese.setSummaryDate(date);

		earningSummaryService.createEarningSummary(ese);



		SessionRepository.closeCurrentSession();
	}

	private void financeDelayWarning() {
		System.out.println("===1");
		FinanceApplicationService financeApplicationService = ComponentFactory.loadClass(FinanceApplicationService.class);
		WarningSchemeService warningSchemeService = ComponentFactory.loadClass(WarningSchemeService.class);
		EnterpriseService enterpriseService = ComponentFactory.loadClass(EnterpriseService.class);
		FinanceBulkstockService financeBulkstockService = ComponentFactory.loadClass(FinanceBulkstockService.class);
		WarningSchemeResultService warningSchemeResultService = ComponentFactory.loadClass(WarningSchemeResultService.class);
		
		List<WarningSchemeEntity> wses = warningSchemeService.inquireWarningSchemeList(WarningFactorEnum.FINANCE_APPLICATION);

		for (WarningSchemeEntity wse : wses) {
			RelationTypeEnum relationType = wse.getRelationType();
			BigDecimal standard = wse.getStandard();
			BigDecimal warning = wse.getWarning();
			StringBuffer sql = new StringBuffer("SELECT * FROM view_fin_finance_delay v where 1 = 1");
			
			Session session = SessionRepository.getCurrentSession();
			List<Object> datas = session.createSQLQuery(sql.toString())
					.addScalar("ENTERPRISE_ID")
					.addScalar("DAYS")
					.addScalar("FINANCE_ID")
					.addScalar("LOAN_TIME_LIMIT")
					.addScalar("LOAN_D8")
					.addScalar("REMAIN_AMOUNT")
					.addScalar("AUDIT_INTEREST")
					.list();

			for (Object l : datas) {
				Object[] os = (Object[])l;
				WarningSchemeResultEntity wsre = new WarningSchemeResultEntity();
				
				wsre.setSettlementStart(DateUtils.fromDateInt((Integer)os[4]));
				wsre.setSettlementEnd(DateUtils.addDateField(DateUtils.fromDateInt((Integer)os[4]), Calendar.DATE, (Integer)os[3]));
				wsre.setFinanceDays((Integer)os[3]);
				wsre.setInterestRate((BigDecimal)os[6]);
				wsre.setDueDays(((BigInteger)os[1]).intValue());
				
				BigDecimal d = new BigDecimal((BigInteger)os[1]);
				if (relationType == RelationTypeEnum.EQ) { //等于
					if (d.compareTo(standard) == 0) {
						wsre.setWarningLevel(WarningLevelEnum.RED);
					} else if (d.compareTo(warning) == 0) {
						wsre.setWarningLevel(WarningLevelEnum.YELLOW);
					} else {
						continue;
					}
				} else if (relationType == RelationTypeEnum.GT) { //大于
					if (d.compareTo(standard) > 0) {
						wsre.setWarningLevel(WarningLevelEnum.RED);
					} else if (d.compareTo(warning) > 0 && d.compareTo(standard) <= 0) {
						wsre.setWarningLevel(WarningLevelEnum.YELLOW);
					} else {
						continue;
					}
				} else if (relationType == RelationTypeEnum.LT) { //小于
					if (d.compareTo(standard) <= 0) {
						wsre.setWarningLevel(WarningLevelEnum.RED);
					} else if (d.compareTo(standard) > 0 && d.compareTo(warning) <= 0) {
						wsre.setWarningLevel(WarningLevelEnum.YELLOW);
					} else {
						continue;
					}
				}

				FinanceApplicationEntity finance = financeApplicationService.inquireFinanceApplicationEntity(((BigInteger) os[2]).longValue());
				if (finance == null) {
					continue;
				}

				List<FinanceBulkstockEntity> fbes = financeBulkstockService.inquireFinanceBulkstockList(finance.getFinanceId());

				EnterpriseEntity enterprise = enterpriseService.inquireEnterprise(finance.getEnterpriseId());

				wsre.setBulkstockId(fbes.get(0).getBulkstockId());
				wsre.setBulkstockInfoId(fbes.get(0).getBulkstockInfoId());
				wsre.setBulkstockName(fbes.get(0).getBulkstockName());
				wsre.setCreateDateTime(DateUtil.now());
				wsre.setEnterpriseId(enterprise.getEnterpriseId());
				wsre.setEnterpriseName(enterprise.getEnterpriseName());
				wsre.setEvaluatePrice(fbes.get(0).getEvaluatePrice());
				wsre.setFactor(WarningFactorEnum.FINANCE_APPLICATION);
				wsre.setFinanceId(finance.getFinanceId());
				wsre.setFinanceNumber(finance.getFinanceNumber());
				wsre.setOperator("系统自动生成");
				wsre.setOperatorTime(DateUtil.now());
				wsre.setSchemeId(wse.getSchemeId());
				wsre.setSchemeName(wse.getSchemeName());
				wsre.setSettlementState(SettlementStateEnum.UNKNOWN);
				
				warningSchemeResultService.createWarningSchemeResult(wsre);

			}
		}
	}

	public void autoCountMonthInterest(Integer y, Integer m, String enterpriseName, Long enterpriseId) {
		SystemParamActionApi systemParamActionApi = ComponentFactory.loadClass(SystemParamActionApi.class);
		MonthEarningService monthEarningService = ComponentFactory.loadClass(MonthEarningService.class);
		MonthBillService monthBillService = ComponentFactory.loadClass(MonthBillService.class);
		MonthEarningDetailService monthEarningDetailService = ComponentFactory.loadClass(MonthEarningDetailService.class);

		//本月收益 
		Integer da = Integer.valueOf(systemParamActionApi.inquireSystemParamByName("结息日"));
		Calendar date = Calendar.getInstance();
		if (m == null && y == null) {
			Calendar c = Calendar.getInstance();
			if (c.get(Calendar.DATE) != da) {
				return;
			}
		} else {
			date.set(y, m, da);
		}

		Integer year = date.get(Calendar.YEAR);
		Integer month = date.get(Calendar.MONTH);

		String sql = "";
		sql = sql + " SELECT                                                            ";
		sql = sql + " 	FINANCE_ID,                                                     ";
		sql = sql + " 	FINANCE_NUMBER,                                                 ";
		sql = sql + " 	ENTERPRISE_ID,                                                  ";
		sql = sql + " 	ENTERPRISE_NAME,                                                ";
		sql = sql + " 	PRODUCT_TYPE,                                                   ";
		sql = sql + " 	AUDIT_INTEREST,                                                 ";
		sql = sql + " 	LOAN_D8,                                                 ";
		sql = sql + " 	SUM(DISBURSEMENT_AMOUNT) DISBURSEMENT_AMOUNT,                   ";
		sql = sql + " 	SUM(RECEIPT_AMOUNT) RECEIPT_AMOUNT,                             ";
		sql = sql + " 	(                                                               ";
		sql = sql + " 		SUM(DISBURSEMENT_AMOUNT) - SUM(RECEIPT_AMOUNT)              ";
		sql = sql + " 	) REMAIN_AMOUNT,                                                ";
		sql = sql + " 	(                                                               ";
		sql = sql + " 		SUM(DISBURSEMENT_AMOUNT) - SUM(RECEIPT_AMOUNT)              ";
		sql = sql + " 	) * (AUDIT_INTEREST / 36000)*"+DateUtils.daysBetween(DateUtils.addDateField(date.getTime(), Calendar.MONTH, -1), date.getTime())+" INTEREST                                   ";
		sql = sql + " FROM                                                              ";
		sql = sql + " 	(                                                               ";
		sql = sql + " 		SELECT                                                      ";
		sql = sql + " 			b.FINANCE_ID,                                           ";
		sql = sql + " 			b.FINANCE_NUMBER,                                       ";
		sql = sql + " 			b.ENTERPRISE_ID,                                        ";
		sql = sql + " 			b.ENTERPRISE_NAME,                                      ";
		sql = sql + " 			b.PRODUCT_TYPE,                                         ";
		sql = sql + " 			b.AUDIT_INTEREST,                                       ";
		sql = sql + " 			a.DISBURSEMENT_AMOUNT,                                  ";
		sql = sql + " 			a.RECEIPT_AMOUNT,                                       ";
		sql = sql + " 			a.STATEMENT_D8,                                         ";
		sql = sql + " 			c.LOAN_D8                                        	    ";
		sql = sql + " 		FROM                                                        ";
		sql = sql + " 			fin_finance_money_statement a,                          ";
		sql = sql + " 			fin_finance_application b,                              ";
		sql = sql + " 			fin_loan_notice c                                       ";
		sql = sql + " 		WHERE                                                       ";
		sql = sql + " 			a.FINANCE_ID = b.FINANCE_ID                             ";
		sql = sql + " 		AND a.FINANCE_ID = c.FINANCE_ID                             ";
		sql = sql + " 		AND (                                                       ";
		sql = sql + " 			a.STATEMENT_SOURCE = 'LOAN_NOTICE'                      ";
		sql = sql + " 			OR a.STATEMENT_SOURCE = 'RECEIVABLES_WAREHOUSE'         ";
		sql = sql + " 			OR a.STATEMENT_SOURCE = 'RECEIVABLES'                   ";
		sql = sql + " 		)                                                           ";
		sql = sql + " 		AND a.STATEMENT_D8 <= "+ DateUtils.parseDateInt(date.getTime()) +" /** 传参条件 */              ";
		sql = sql + " 	) t                                                             ";
		sql = sql + " GROUP BY                                                          ";
		sql = sql + " 	t.FINANCE_ID                                                    ";
		sql = sql + " HAVING                                                            ";
		sql = sql + " 	REMAIN_AMOUNT > 0                                               ";

		System.out.println(sql);

		Session session = SessionRepository.getCurrentSession();
		List<Object> datas = session.createSQLQuery(sql.toString())
				.addScalar("FINANCE_ID")
				.addScalar("FINANCE_NUMBER")
				.addScalar("ENTERPRISE_ID")
				.addScalar("ENTERPRISE_NAME")
				.addScalar("PRODUCT_TYPE")
				.addScalar("REMAIN_AMOUNT")
				.addScalar("AUDIT_INTEREST")
				.addScalar("INTEREST")
				.addScalar("LOAN_D8")
				.list();

		List<MonthEarningDetailEntity> medes = monthEarningDetailService.inquiryMonthEarningList(year, month, null, null, null);
		for (MonthEarningDetailEntity mede : medes) {
			monthEarningDetailService.disableMonthEarning(mede.getMonthEarningDetailId());
		}

		for (Object l : datas) {
			Object[] os = (Object[])l;
			MonthEarningDetailEntity mede = new MonthEarningDetailEntity();
			mede.setFinanceId(((BigInteger) os[0]).longValue());
			mede.setFinanceNumber((String) os[1]);
			mede.setEnterpriseId(((BigInteger) os[2]).longValue());
			mede.setEnterpriseName((String) os[3]);
			mede.setProductType(ProductTypeEnum.valueOf(((Byte)os[4]).intValue()));
			mede.setValuationAmount((BigDecimal) os[5]);
			mede.setInterestRate((BigDecimal) os[6]);
			mede.setShouldPay((BigDecimal) os[7]);
			mede.setLoanDate(DateUtils.fromDateInt((Integer) os[8]));
			mede.setPayMethod("按月付息到期还本");
			mede.setSettlementStart(DateUtils.addDateField(date.getTime(), Calendar.MONTH, -1));
			mede.setSettlementEnd(date.getTime());
			mede.setYear(year);
			mede.setMonth(month);
			mede.setPaid(BigDecimal.ZERO);
			monthEarningDetailService.createMonthEarningDetail(mede);
		}

		sql = "";
		sql = sql + " SELECT                                         ";
		sql = sql + " 	PRODUCT_TYPE,                                ";
		sql = sql + " 	SUM(VALUATION_AMOUNT) VALUATION_AMOUNT,      ";
		sql = sql + " 	SUM(SHOULD_PAY) SHOULD_PAY                   ";
		sql = sql + " FROM                                           ";
		sql = sql + " 	FIN_MONTH_EARNING_DETAIL                     ";
		sql = sql + " GROUP BY                                       ";
		sql = sql + " 	PRODUCT_TYPE;                                ";
		session = SessionRepository.getCurrentSession();
		datas = session.createSQLQuery(sql.toString())
				.addScalar("PRODUCT_TYPE")
				.addScalar("VALUATION_AMOUNT")
				.addScalar("SHOULD_PAY")
				.list();

		System.out.println(sql);
		MonthBillEntity mbe = new MonthBillEntity();
		for (Object l : datas) {
			Object[] os = (Object[])l;
			switch (((Integer)os[0]).intValue()) {
			case 1:
				mbe.setBulkstockValuation1((BigDecimal) os[1]);
				mbe.setBulkstockIntrerst1((BigDecimal) os[2]);
				break;
			case 2:
				mbe.setBulkstockValuation2((BigDecimal) os[1]);
				mbe.setBulkstockIntrerst2((BigDecimal) os[2]);
				break;
			case 3:
				mbe.setBulkstockValuation3((BigDecimal) os[1]);
				mbe.setBulkstockIntrerst3((BigDecimal) os[2]);
				break;
			case 4:
				mbe.setBulkstockValuation4((BigDecimal) os[1]);
				mbe.setBulkstockIntrerst4((BigDecimal) os[2]);
				break;
			case 5:
				mbe.setBulkstockValuation5((BigDecimal) os[1]);
				mbe.setBulkstockIntrerst5((BigDecimal) os[2]);
				break;
			case 6:
				mbe.setBulkstockValuation6((BigDecimal) os[1]);
				mbe.setBulkstockIntrerst6((BigDecimal) os[2]);
				break;
			default:
				break;
			}
			mbe.setMonth(month);
			mbe.setYear(year);
		}
		List<MonthBillEntity> mbes = monthBillService.selectMonthBillDetail(year, month);
		for (MonthBillEntity mm : mbes) {
			monthBillService.disableMonthBill(mm.getMonthBillId());
		}
		monthBillService.createMonthBill(mbe);

		sql = "";
		sql = sql + " SELECT                                        ";
		sql = sql + " 	a.ENTERPRISE_ID ENTERPRISE_ID,              ";
		sql = sql + " 	a.ENTERPRISE_NAME ENTERPRISE_NAME,          ";
		sql = sql + " 	SUM(a.VALUATION_AMOUNT) VALUATION_AMOUNT,   ";
		sql = sql + " 	SUM(a.SHOULD_PAY) SHOULD_PAY,               ";
		sql = sql + " 	SUM(IFNULL(a.PAID,0)) PAID,                 ";
		sql = sql + " 	SUM(c.DISBURSEMENT_AMOUNT) LOAN_AMOUNT,     ";
		sql = sql + " 	b.PRODUCT_TYPE PRODUCT_TYPE    				";
		sql = sql + " FROM                                          ";
		sql = sql + " 	FIN_MONTH_EARNING_DETAIL a,                 ";
		sql = sql + " 	fin_finance_application b,                  ";
		sql = sql + " 	fin_finance_money_statement c               ";
		sql = sql + " WHERE                                         ";
		sql = sql + " 	a.ENTERPRISE_ID = b.ENTERPRISE_ID           ";
		sql = sql + " AND b.FINANCE_ID = c.FINANCE_ID               ";
		sql = sql + " AND c.STATEMENT_SOURCE = 'LOAN_NOTICE'        ";
		sql = sql + " GROUP BY                                      ";
		sql = sql + " 	ENTERPRISE_ID, b.PRODUCT_TYPE;                              ";
		System.out.println(sql.toString());

		session = SessionRepository.getCurrentSession();
		datas = session.createSQLQuery(sql.toString())
				.addScalar("ENTERPRISE_ID")
				.addScalar("ENTERPRISE_NAME")
				.addScalar("VALUATION_AMOUNT")
				.addScalar("SHOULD_PAY")
				.addScalar("PAID")
				.addScalar("LOAN_AMOUNT")
				.addScalar("PRODUCT_TYPE")
				.list();


		List<MonthEarningEntity> mees = monthEarningService.inquiryMonthEarningList(year, month, null, null, null, null);
		for (MonthEarningEntity mee : mees) {
			monthEarningService.disabledMonthEarning(mee.getMonthEarningId());
		}

		Map<Long, MonthEarningEntity> map = new HashMap<>();
		for (Object l : datas) {
			Object[] os = (Object[])l;
			MonthEarningEntity entity = null;
			if (map.get(((BigInteger) os[0]).longValue()) != null) {
				entity = map.get(((BigInteger) os[0]).longValue());
			} else {
				entity = new MonthEarningEntity();
			}
			entity.setEarningDate(date.getTime());
			entity.setEnterpriseId(((BigInteger) os[0]).longValue());
			entity.setEnterpriseName((String) os[1]);
			entity.setFinancingAmount((BigDecimal) os[5]);
			entity.setRemainingMoney((BigDecimal) os[2]);
			entity.setRepaidFee(BigDecimal.ZERO);
			entity.setRepayingFee(entity.getRepayingFee().add((BigDecimal) os[3]));
			entity.setMonth(month);
			entity.setYear(year);

			switch (((Byte)os[6]).intValue()) {
			case 1:
				entity.setAmount1((BigDecimal) os[2]);
				entity.setInterest1((BigDecimal) os[3]);
				break;
			case 2:
				entity.setAmount2((BigDecimal) os[2]);
				entity.setInterest2((BigDecimal) os[3]);
				break;
			case 3:
				entity.setAmount3((BigDecimal) os[2]);
				entity.setInterest3((BigDecimal) os[3]);
				break;
			case 4:
				entity.setAmount4((BigDecimal) os[2]);
				entity.setInterest4((BigDecimal) os[3]);
				break;
			case 5:
				entity.setAmount5((BigDecimal) os[2]);
				entity.setInterest5((BigDecimal) os[3]);
				break;
			case 6:
				entity.setAmount6((BigDecimal) os[2]);
				entity.setInterest6((BigDecimal) os[3]);
				break;
			default:
				break;
			}

			entity.setMonth(month);
			entity.setYear(year);
			map.put(((BigInteger) os[0]).longValue(), entity);
		}

		for (Long in : map.keySet()) {
			MonthEarningEntity k = map.get(in);//得到每个key多对用value的值
			monthEarningService.createMonthEarning(k);
		}

		SessionRepository.closeCurrentSession();
	}

	public void initEnterpriseEnterprise(Long enterpriseId) {

		EnterpriseService enterpriseService = ComponentFactory.loadClass(EnterpriseService.class);
		FinanceApplicationService financeApplicationService = ComponentFactory.loadClass(FinanceApplicationService.class);
		EnterpriseGradeService enterpriseGradeService = ComponentFactory.loadClass(EnterpriseGradeService.class);
		FinanceMoneyStatementService financeMoneyStatementService = ComponentFactory.loadClass(FinanceMoneyStatementService.class);
		ContainerInventoryService containerInventoryService = ComponentFactory.loadClass(ContainerInventoryService.class);
		EnterpriseFinanceSummaryService enterpriseFinanceSummaryService = ComponentFactory.loadClass(EnterpriseFinanceSummaryService.class);

		List<EnterpriseFinanceSummaryEntity> efses = enterpriseFinanceSummaryService.inquireEnterpriseFinanceSummaryList(null, null);
		for (EnterpriseFinanceSummaryEntity efse : efses) {
			EnterpriseEntity e = enterpriseService.inquireEnterprise(efse.getEnterpriseId());
			if (e == null || e.getEnabled() == Boolean.FALSE) {
				enterpriseFinanceSummaryService.deleteEnterpriseFinanceSummary(efse.getEnterpriseId());
			}
		}


		// 扣除 状态为 取消/审批不通过/待提交/待确认
		Set<FinanceStateEnum> financeStates = CollectionUtils.convertSet(FinanceStateEnum.values());
		financeStates.remove(FinanceStateEnum.CANCEL);
		financeStates.remove(FinanceStateEnum.APPROVE_NOPASS);
		financeStates.remove(FinanceStateEnum.UNSUMIT);
		financeStates.remove(FinanceStateEnum.WAIT_CONFIRM);

		//流水
		List<FinanceMoneyStatementEntity> fmses = financeMoneyStatementService.inquireFinanceMoneyStatementList(0L);
		for (FinanceMoneyStatementEntity fmse: fmses) {
			FinanceApplicationEntity finance = null;
			if (fmse.getFinanceId() != null) {
				finance = financeApplicationService.inquireFinanceApplicationEntity(fmse.getFinanceId());
			}
			//			if (finance == null && fmse.getFinanceId() != null) {
			//				financeMoneyStatementService.deleteFinanceMoneyStatement(fmse.getMoneyStatementId());
			//			}
		}

		//箱列表
		List<ContainerInventoryEntity> cies = containerInventoryService.inquireContainerInventoryList("", null, null);
		for (ContainerInventoryEntity cie : cies) {
			FinanceApplicationEntity finance = null;
			EnterpriseEntity enterprise = null;
			if (cie.getFinanceId() != null) {
				finance = financeApplicationService.inquireFinanceApplicationEntity(cie.getFinanceId());
			}
			if (cie.getEnterpriseId() != null) {
				enterprise = enterpriseService.inquireEnterprise(cie.getEnterpriseId());
			}

			if (finance == null || enterprise == null) {
				containerInventoryService.deleteContainerInventory(cie.getInventoryId());
			}
		}

		//企业列表
		List<EnterpriseEntity> ees = enterpriseService.inquireEnterpriseList1(enterpriseId);
		if (ees != null && !ees.isEmpty()) {
			for (EnterpriseEntity ee : ees) {

				EnterpriseGradeEntity ege = enterpriseGradeService.inquireEnterpriseGrade(ee.getEnterpriseId());
				if (ege == null) {
					continue;
				}

				ege.setCreditAlready(BigDecimal.ZERO);
				List<FinanceMoneyStatementEntity> fmses1 = financeMoneyStatementService.inquireFinanceMoneyStatementList1(ee.getEnterpriseId(), new String[]{"LOAN_NOTICE"}, null, null);
				for (FinanceMoneyStatementEntity fmse : fmses1) {
					ege.setCreditAlready(ege.getCreditAlready().add(fmse.getDisbursementAmount()));
				}

				//融资申请
				//				List<FinanceApplicationEntity> financeList = financeApplicationService.inquireFinanceList(enterpriseId, financeStates);
				//				for (FinanceApplicationEntity fae : financeList) {
				//					ege.setCreditAlready(ege.getCreditAlready().add(fae.getFinanceAmount()));
				//				}

				//收款流水
				List<FinanceMoneyStatementEntity> fmses2 = financeMoneyStatementService.inquireFinanceMoneyStatementList1(ee.getEnterpriseId(), new String[]{"RECEIVABLES", "RECEIVABLES_WAREHOUSE"}, null, null);
				for (FinanceMoneyStatementEntity fmse : fmses2) {
					ege.setCreditAlready(ege.getCreditAlready().subtract(fmse.getReceiptAmount()));
				}

				enterpriseGradeService.persistEnterpriseGrade(ege);
			}
		}
	}
}
